/*
 * Ubiquity command gd-upload
 */
CmdUtils.CreateCommand({
  names: ["google docs upload", "gd-upload"],
  icon: "https://docs.google.com/images/doclist/icon_4_doc.gif",
  homepage: "http://boardraider-ubiquity-commands.googlecode.com/svn/trunk/gd-upload.html",
  author: {name: "boardraider"},
  license: "Public Domain",
  description: "Uploads a document to Google Docs via URL.",
  help: "First login to Google Docs before using this command.",
  arguments: [{
               role: "object",
               nountype: noun_arb_text,
               label: "URL"
             }],
  
  preview: function(pblock, input) {
    var text = _("documents");
    if (input && input.object.text.length > 0) {
      text = input.object.text;
    }
    pblock.innerHTML = _("Uploads ") + text + _(" to your Google Docs account");
  },
   
  execute: function(input) {
    getToken(encodeURI(decodeURI(input.object.text)));
  }
  
});

/*
 * Gets the security token from Google.
 *
 * Params:
 * aURL - location of the document
 */
function getToken(aURL) {
  xhr = new XMLHttpRequest();
  // Google Docs upload form
  xhr.open('GET', 'https://docs.google.com/DocAction?action=updoc&classic=true');
  xhr.onreadystatechange = function (aEvent) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var pattern = /<input type="hidden" name="security_token" value="([^"]+)">/;
        var matches = xhr.responseText.match(pattern);
        if (matches) { // retrieved security token successfully
          sendDoc(matches[1], aURL);
        } else { // failed to retrieve security token - not logged in?
          displayMessage(_("Please login first!"));
          Utils.openUrlInBrowser('https://docs.google.com/DocAction?action=updoc&classic=true');
        }
      } else { // server error
        displayMessage(_("Error getting token!"));
      }
    }
  }
  xhr.send(null);
}

/*
 * Uploads the document to Google Docs.
 *
 * Params:
 * aToken - Google Docs security token
 * aURL - location of the document
 */
function sendDoc(aToken, aURL) {
  xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://docs.google.com/DocAction?action=updoc');
  // building post data
  var boundaryString = '-gd-upload---';
  var boundary = '--' + boundaryString;
  var postData = ['', boundary, 'Content-Disposition: form-data; name="security_token"', '', aToken,
    boundary, 'Content-Disposition: form-data; name="formsubmitted"', '', 'true', boundary,
    'Content-Disposition: form-data; name="uploadURL"', '', aURL, boundary + '--'].join('\r\n');
  xhr.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundaryString);
  xhr.setRequestHeader('Content-length', postData.length);
  xhr.onreadystatechange = function (aEvent) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      Utils.openUrlInBrowser(xhr.channel.URI.spec);
    }
  }
  xhr.send(postData);
}
